package yxy.game.pm2.command.wuchao;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.wuchaolvreward;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.WuchaoMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.wuchao.WuchaoModule;

/** 乌巢 乌巢攻占奖励领取 */
@MessageType(proto = Command.WuchaoBox, classtype = WuchaoMessage.WuchaoBoxRequest.class)
public class CMD_WuchaoBox extends Command<WuchaoMessage.WuchaoBoxRequest> {

	@Override
	public void execute(MessageSource messageSource, WuchaoMessage.WuchaoBoxRequest request) {
		String playerCode = messageSource.getTag();
		int boxId = request.getBox();

		WuchaoMessage.WuchaoBoxResponse.Builder response = WuchaoMessage.WuchaoBoxResponse.newBuilder();

		WuchaoModule wuchaoModule = WuchaoModule.get(playerCode);
		if (wuchaoModule.getStage() <= 0) {
			send(messageSource, response, Result.WuchaoNotStart);// 没有开始挑战
			return;
		}
		for (Integer box : wuchaoModule.getBox()) {
			if (box == boxId) {
				send(messageSource, response, Result.WuchaoBoxHasRewarded);// 已经领取过
				return;
			}
		}

		wuchaolvreward data = DataCenter.getData(boxId, wuchaolvreward.class);
		if (data == null) {
			send(messageSource, response, Result.ParamError);// 宝箱id错误
			return;
		}

		if (data.getCondition() > wuchaoModule.getPassStage()) {
			send(messageSource, response, Result.WuchaoBoxCannotGet);// 尚未通关，不能领取
			return;
		}

		try {
			if (wuchaoModule.tryLock()) {

				Currencies rewards = new Currencies(Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum()));
				new CurrencyHandle().addCurrency(playerCode, CCReason.乌巢之战, rewards);

				wuchaoModule.getBox().add(data.getId());
				wuchaoModule.set();

				response.addAllRewards(new CurrencyHandle().packItems(rewards));
				for (Integer box : wuchaoModule.getBox()) {
					response.addBox(box);// 已领宝箱id
				}

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			wuchaoModule.unlock();
		}
	}

	private void send(MessageSource messageSource, WuchaoMessage.WuchaoBoxResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}